package cn.ztuo.bitrade.controller.contract;

import cn.ztuo.bitrade.constant.SysConstant;
import cn.ztuo.bitrade.controller.common.BaseAdminController;
import cn.ztuo.bitrade.entity.ContractPriceControl;
import cn.ztuo.bitrade.service.ContractPriceControlService;
import cn.ztuo.bitrade.util.BeanUtils;
import cn.ztuo.bitrade.util.DateUtil;
import cn.ztuo.bitrade.util.MessageResult;
import cn.ztuo.bitrade.util.RedisUtil;
import cn.ztuo.bitrade.vo.contractPriceControlVo.ContractPriceControlAddReqVo;
import cn.ztuo.bitrade.vo.contractPriceControlVo.ContractPriceControlFindReqVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;


@RestController
@RequestMapping("contract/contract-price-control")
@Api(value = "平台价格控制器相关的api",tags = "平台价格控制器相关的api")
public class ContractPriceControlController extends BaseAdminController {
    @Autowired
    private ContractPriceControlService service;
    @Autowired
    private RedisUtil redisUtil;
    @Resource(name = "contractPriceControlSymbols")
    private Map<String, TreeMap<Date, ContractPriceControl>> contractPriceControlSymbols;

    @ApiOperation(value = "新增/修改控制价格", notes = "新增/修改控制价格 新增不传id,修改必须传id")
    @RequestMapping(value = "/saveAndUpdate", method = RequestMethod.POST)
    public MessageResult saveAndUpdate(@Validated ContractPriceControlAddReqVo reqVo) throws ParseException {
        long seconds = reqVo.getSeconds();
        Calendar calendar = new GregorianCalendar();
        String startTimeStr = reqVo.getStartTime().replace("T", " ").replace("000.Z", "");
        Date startTime = DateUtil.datehhmmss(startTimeStr);
        reqVo.setStartTimeDate(startTime);
        calendar.setTime(startTime);
        calendar.add(Calendar.SECOND,(int)seconds); //把日期往后增加一天,整数  往后推,负数往前移动
        Date endTime=calendar.getTime(); //这个时间就是日期往后推一天的结果
        reqVo.setEndTimeDate(endTime);

        if(reqVo.getId()!=null&&reqVo.getStatus()!=null){
            Long id = reqVo.getId();
            Integer status = reqVo.getStatus();
            ContractPriceControl contractPriceControl = service.get(id);
            if(contractPriceControl.getStatus().intValue()!=status.intValue()){
                contractPriceControl = contractPriceControlSymbols.get(contractPriceControl.getSymbol()).get(contractPriceControl.getStartTime());

                if(contractPriceControl==null){
                    return MessageResult.error("该控制器已失效,请核实后操作");
                }

                String key = SysConstant.CONTRACT_PRICE_CONTROL + contractPriceControl.getSymbol() + ":";
                if (status == 0) {
                    if (contractPriceControl.getStatus() == 2) {
                        contractPriceControl.setStatus(status);
                    }
                }
                if (status == 2) {
                    if (contractPriceControl.getStatus() == 1) {
                        if (redisUtil.hasKey(key)) {
                            redisUtil.delete(key);
                        }
                    }
                    contractPriceControl.setStatus(status);
                    service.saveAndFlush(contractPriceControl);
                }
                if (status == 3) {
                    if (contractPriceControl.getStatus() == 1) {
                        if (redisUtil.hasKey(key)) {
                            redisUtil.delete(key);
                        }
                    }
                    contractPriceControlSymbols.get(contractPriceControl.getSymbol()).remove(contractPriceControl.getStartTime());
                    contractPriceControl.setStatus(status);
                    service.saveAndFlush(contractPriceControl);
                }
                return MessageResult.getSuccessInstance("", contractPriceControl);
            }
        }



        if(startTime.before(new Date())){
            return MessageResult.error("开始时间必须大于当前时间,请核实后操作!");
        }
        if(endTime.before(new Date())){
            return MessageResult.error("持续时长(秒)必须大于0,请核实后操作!");
        }
        if (!service.isTimeOk(reqVo)) {
            return MessageResult.error("开始时间冲突,请核实后操作!");
        }
        ContractPriceControl contractPriceControl = service.saveAndFlush(reqVo);
        if (contractPriceControl != null) {
            contractPriceControlSymbols.get(contractPriceControl.getSymbol()).put(contractPriceControl.getStartTime(), contractPriceControl);
        }
        return MessageResult.getSuccessInstance("", contractPriceControl);
    }

    @ApiOperation(value = "列表查询", notes = "列表查询分页")
    @RequestMapping(value = "/findAll", method = RequestMethod.POST)
    public MessageResult findAll(@Validated ContractPriceControlFindReqVo reqVo) {
        List<ContractPriceControl> list = service.findAll(reqVo);
        return MessageResult.getSuccessInstance("", list);
    }
    @ApiOperation(value = "列表查询分页", notes = "列表查询分页")
    @RequestMapping(value = "/findAllByPage", method = RequestMethod.POST)
    public MessageResult findAllByPage(@Validated ContractPriceControlFindReqVo reqVo) {
        Page<ContractPriceControl> page = service.findAllByPage(reqVo);
        return MessageResult.getSuccessInstance("", page);
    }

    @ApiOperation(value = "获取详情", notes = "获取详情")
    @RequestMapping(value = "/getById", method = RequestMethod.POST)
    public MessageResult getById(Long id) {
        ContractPriceControl contractPriceControl = service.get(id);
        return MessageResult.getSuccessInstance("", contractPriceControl);
    }

    @ApiOperation(value = "操作", notes = "操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "Long",required = true),
            @ApiImplicitParam(name = "status", value = "状态  0:开启  2:暂停 3:结束(取消)", dataType = "int",required = true)}
    )
    @RequestMapping(value = "/operation", method = RequestMethod.POST)
    public MessageResult cancel(Long id, int status) {
        ContractPriceControl contractPriceControl = service.get(id);
        contractPriceControl = contractPriceControlSymbols.get(contractPriceControl.getSymbol()).get(contractPriceControl.getStartTime());

        if(contractPriceControl==null){
            return MessageResult.error("该控制器已失效,请核实后操作");
        }

        String key = SysConstant.CONTRACT_PRICE_CONTROL + contractPriceControl.getSymbol() + ":";
        if (status == 0) {
            if (contractPriceControl.getStatus() == 2) {
                contractPriceControl.setStatus(status);
            }
        }
        if (status == 2) {
            if (contractPriceControl.getStatus() == 1) {
                if (redisUtil.hasKey(key)) {
                    redisUtil.delete(key);
                }
            }
            contractPriceControl.setStatus(status);
            service.saveAndFlush(contractPriceControl);
        }
        if (status == 3) {
            if (contractPriceControl.getStatus() == 1) {
                if (redisUtil.hasKey(key)) {
                    redisUtil.delete(key);
                }
            }
            contractPriceControlSymbols.get(contractPriceControl.getSymbol()).remove(contractPriceControl.getStartTime());
            contractPriceControl.setStatus(status);
            service.saveAndFlush(contractPriceControl);
        }
        return MessageResult.getSuccessInstance("", contractPriceControl);
    }
}
